/* eslint-disable no-param-reassign */
import { Button, Dialog, Form, List } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';

const FromItem = Form.Item;

/**
 * 对象扁平化
 * @param {*} obj 数据源
 * @param {*} parentKey
 * @param {*} result 返回
 * @returns
 */
function flattenObject(obj, parentKey = '', result = {}) {
  for (const key in obj) {
    // eslint-disable-next-line @iceworks/best-practices/recommend-polyfill, no-prototype-builtins
    if (obj.hasOwnProperty(key)) {
      const newKey = parentKey ? `${parentKey}.${key}` : key;

      if (typeof obj[key] === 'object' && obj[key] !== null) {
        flattenObject(obj[key], newKey, result);
      } else {
        result[newKey] = obj[key];
      }
    }
  }
  return result;
}

const DataForm = ({ modal, userInfo, onCancel }) => {
  // 使用useRef进行拼接字段且不会造成重绘
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [log] = useState(() => observable({}));
  const [list, setList] = useState([]);
  useEffect(() => { if (modal[1]?.startsWith?.('toClose') || modal[2]?.startsWith?.('toClose')) handleCancel(); }, [modal]);
  useEffect(() => {
    (async () => {
      if (JSON.stringify(userInfo) !== '{}') {
        const data = userInfo;
        editCtx.origin = _.cloneDeep(data);
        _.assign(log, data);
        if (JSON.stringify(data?.args) !== '{}') {
          const res = flattenObject(data.args);
          // eslint-disable-next-line @iceworks/best-practices/recommend-polyfill
          const mapList = Object.entries(res).map(([key, value]) => ({
            title: key,
            value,
          }));
          setList([...mapList]);
        }
      }
    })();
  }, []);

  const handleCancel = () => {
    onCancel?.();
  };

  return (
    <>
      <List
        size="small"
        header={<div>参数列表</div>}
        dataSource={list}
        renderItem={(item, i) => (
          <List.Item
            key={i}
            extra={item.value}
            title={`args : ${item.title}`}
          />
        )}
      />
      <DrawerFooter>
        <FromItem>
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </>

  );
};

export default observer(DataForm);
